package update;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ListenerContainer<T> {
	
	protected List<T> listeners, addListeners, removeListeners;
	protected boolean iterating;
	
	public ListenerContainer() {
		listeners = new ArrayList<T>();
		addListeners = new ArrayList<T>();
		removeListeners = new ArrayList<T>();
	}
	
	public void callMethod(Method method, Object... args) {
		iterating = true;
		
		for(T l : listeners) {
			try {
				method.invoke(l, args);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		iterating = false;
		
		for(T l : addListeners) {
			listeners.add(l);
		}
		addListeners.clear();
		
		for(T l : removeListeners) {
			listeners.remove(l);
		}
		removeListeners.clear();
	}
	
	public void addListener(T l ) {
		assert(l != null);
		
		if(iterating) addListeners.add(l);
		else listeners.add(l);
	}
	
	public void removeListener(T l) {
		assert(l != null);
		
		if(iterating) removeListeners.add(l);
		else listeners.remove(l);
	}
	
	public void cleanUp() {
		listeners.clear();
		addListeners.clear();
		removeListeners.clear();
	}
}